package com.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

public class BaseDao {

    public Connection getCon(){

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        Connection  con = null;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bbs_message?useSSL=false&characterEncoding=utf-8","root","root");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    public List<?> query(String sql,Object[] obj,Class<?> cls){
        List<Object> list = new ArrayList<Object>();
        Connection con = getCon();
        PreparedStatement ps;
        Method m = null;
        try {
            ps = con.prepareStatement(sql);
            if(obj != null && obj.length > 0){
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject(i+1, obj[i]);
                }
            }
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                try {
                    Object o = cls.newInstance();
                    ResultSetMetaData md = rs.getMetaData();
                    int count =  md.getColumnCount();
                    for (int i = 0; i < count; i++) {
                        Field f = cls.getDeclaredField(md.getColumnName(i+1));
                        if(rs.getObject(i+1) != null){
                            f.setAccessible(true);
                            f.set(o, rs.getObject(i+1));
                        }
                    }
                    list.add(o);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public int saveOrUpdateORDel(String sql,Object[] obj){
        Connection con = getCon();
        try {
            PreparedStatement ps = con.prepareStatement(sql);
            if(obj != null && obj.length > 0){
                for (int i = 0; i < obj.length; i++) {
                    ps.setObject(i+1, obj[i]);
                }
            }
            int res = ps.executeUpdate();
            return res;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
